package com.example.nekoneko.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.nekoneko.common.Result;
import com.example.nekoneko.dao.User;
import com.example.nekoneko.exception.ServiceException;
import com.example.nekoneko.service.UserService;
import com.example.nekoneko.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    /*
    新增用户信息
    * */
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try{
            userService.save(user);
        }catch (Exception e){
            if (e instanceof DuplicateKeyException){
                return Result.error("数据库插入失败");
            }else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }
    /*
    * 修改用户信息*/
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.success();
    }
    /*删除用户信息*/
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        User currentUser = TokenUtils.getCurrentUser();
        if (id.equals(currentUser.getId())){
            throw new ServiceException("不能删除当前的用户");
        }
        userService.removeById(id);
        return Result.success();
    }
    /*查询全部用户信息*/
    @GetMapping("/selectAll")
    public Result selectAll(){
        List<User> userList = userService.list(new QueryWrapper<User>().orderByDesc("id"));//select * from user order by id desc
        return Result.success(userList);
    }
    /*根据id查询用户信息*/
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        User user = userService.getById(id);
        return Result.success(user);
    }


}
